package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.tanhua.domain.Admin;
import com.itheima.tanhua.dto.AdminDto;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.utils.JwtUtils;
import com.itheima.tanhua.vo.AdminVo;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AdminMapper;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Map login(AdminDto adminDto) {
        if (StringUtils.isEmpty(adminDto.getVerificationCode())) {
            throw new BusinessException("验证码不能为空！");
        }
        //从缓存中拿取验证码
        String code = redisTemplate.opsForValue().get(Constants.ADMIN_CODE + adminDto.getUuid());
        //清楚缓存
        redisTemplate.delete(Constants.ADMIN_CODE + adminDto.getUuid());
        if (!adminDto.getVerificationCode().equals(code)) {
            throw new BusinessException("验证码错误！");
        }
        //校验数据库 根据用户名查询 有再校验密码
        LambdaQueryWrapper<Admin> qw = Wrappers.lambdaQuery(Admin.class);
        qw.eq(Admin::getUsername, adminDto.getUsername());
        Admin login = adminMapper.selectOne(qw);
        if (login == null) {
            throw new BusinessException("用户名不存在！");
        }
        //校验密码
        if (!DigestUtils.md5DigestAsHex(adminDto.getPassword().getBytes()).equals(login.getPassword())) {
            throw new BusinessException("密码错误！");
        }
        Map tokenMap = new HashMap();
        tokenMap.put("username", login.getUsername());
        tokenMap.put("id", login.getId());
        //获取token
        String token = JwtUtils.getToken(tokenMap);
        tokenMap.clear();
        tokenMap.put("token", token);
        return tokenMap;
    }


    /**
     * 获取用户详情信息
     *
     * @param userId
     * @return
     */
    public AdminVo findAdminById(Long userId) {
        Admin admin = adminMapper.selectById(userId);
        AdminVo result = AdminVo.init(admin);
        return result;
    }
}
